package com.yuexunit.operationman.nbsy.module.OperationRiskAssessment.ui;

import android.content.Context;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;

import com.yuexunit.operationman.nbsy.R;
import com.yuexunit.operationman.nbsy.base.BaseKJActivity;
import com.yuexunit.operationman.nbsy.base.ExitApplication;
import com.yuexunit.operationman.nbsy.base.SubmitBean;
import com.yuexunit.operationman.nbsy.config.AppConfig;
import com.yuexunit.operationman.nbsy.module.OperationRiskAssessment.bean.RiskAssessmentBean;
import com.yuexunit.operationman.nbsy.module.OperationRiskAssessment.model.impl.RiskAssessmentModel;
import com.yuexunit.operationman.nbsy.module.OperationRiskAssessment.presenter.IRiskAssessmentPresenter;
import com.yuexunit.operationman.nbsy.module.OperationRiskAssessment.presenter.impl.RiskAssessmentPresenter;
import com.yuexunit.operationman.nbsy.module.OperationRiskAssessment.ui.view.IRiskAssessmentView;
import com.yuexunit.operationman.nbsy.module.SafeOperation.bean.SignBean;
import com.yuexunit.operationman.nbsy.module.SafeOperation.model.impl.SafeOperationSignModel;
import com.yuexunit.operationman.nbsy.module.SafeOperation.presenter.ISafeOperationSignPresenter;
import com.yuexunit.operationman.nbsy.module.SafeOperation.presenter.impl.SafeOperationSignPresenter;
import com.yuexunit.operationman.nbsy.module.SafeOperation.ui.view.ISafeOperationSignView;
import com.yuexunit.operationman.nbsy.widget.ActionSheetDialog;
import com.yuexunit.operationman.nbsy.widget.ClickDialog;
import com.yuexunit.operationman.nbsy.widget.LoadingDialog;
import com.yuexunit.operationman.nbsy.widget.LoginDialog;

import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by chenss on 2017/8/9 0009.
 */

public class Act_RiskAssessmentTime extends BaseKJActivity implements ISafeOperationSignView, IRiskAssessmentView {

    @Bind(R.id.tv_patient_name)
    TextView tvPatientName;
    @Bind(R.id.tv_patient_sex)
    TextView tvPatientSex;
    @Bind(R.id.tv_patient_visitno)
    TextView tvPatientVisitno;
    @Bind(R.id.tv_patient_disease)
    TextView tvPatientDisease;
    @Bind(R.id.radio_01)
    RadioButton radio01;
    @Bind(R.id.radio_02)
    RadioButton radio02;

    //签名
    @Bind(R.id.img_ra_sign_03)
    ImageView imgRaSign03;
    @Bind(R.id.btn_ra_sign_03)
    TextView btnRaSign03;
    @Bind(R.id.tv_ra_sign_03_time)
    TextView tvRaSign03Time;
    @Bind(R.id.tv_ra_sign_03_name)
    TextView tvRaSign03Name;

    LoadingDialog loadingDialog;
    IRiskAssessmentPresenter presenter;
    private int original_score = 0;

    LoginDialog loginDialog;
    ISafeOperationSignPresenter presenter_sign;

    ClickDialog dialog;

    @Override
    public void setRootView() {
        setContentView(R.layout.act_riskassessmenttime);
        ButterKnife.bind(this);
        ExitApplication.getInstance().addActivity(this);
    }

    @Override
    public void initData() {
        super.initData();
        loginDialog = new LoginDialog(aty);
        loadingDialog = new LoadingDialog(this);
        presenter = new RiskAssessmentPresenter(this, new RiskAssessmentModel());
        presenter_sign = new SafeOperationSignPresenter(this, new SafeOperationSignModel());
        setTitle();
        setContent();
    }

    private void setTitle() {
        tvPatientName.setText(AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().getPatientName());
        if (AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().getPatientSex().equals("1")) {
            tvPatientSex.setText("男");
        } else if (AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().getPatientSex().equals("2")) {
            tvPatientSex.setText("女");
        } else {
            tvPatientSex.setText("不详");
        }
        tvPatientVisitno.setText("住院号" + AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().getInHospitalNo());
        tvPatientDisease.setText(PreferenceHelper.readString(aty, AppConfig.PATIENT_INFO, AppConfig.PATIENT_DISEASE));
    }

    private void setContent() {
        if (AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().getNursesSign() != null) {
            imgRaSign03.setVisibility(View.VISIBLE);
            btnRaSign03.setVisibility(View.GONE);
            tvRaSign03Time.setVisibility(View.VISIBLE);
            tvRaSign03Name.setVisibility(View.VISIBLE);
            Glide.with(aty)
                    .load(AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().getNursesSignUrl())
                    .placeholder(R.color.white)
                    .error(R.color.white)
                    .into(imgRaSign03);
            tvRaSign03Time.setText("签名时间:" + AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().getNursesSignTimeStr());
            tvRaSign03Name.setText(AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().getNursesSign());
        }

        for (RiskAssessmentBean.ObjectEntity.RiskItemListEntity p : AppConfig.RISKASSESSMENTBEAN.getObject().getRiskItemList()) {
            switch (p.getItemCode()) {
                case "SJ_T":
                    if (p.getItemValue().length() > 0) {
                        String[] skin = p.getItemValue().split(";", -1);
                        if (skin[0].equals("1")) {
                            original_score = 0;
                            radio01.setChecked(true);
                        }
                        if (skin[0].equals("2")) {
                            original_score = 1;
                            radio02.setChecked(true);
                        }
                    }
                    break;
            }
        }
    }


    @OnClick({R.id.titlebar_docadvice_img_back, R.id.sure, R.id.btn_ra_sign_03})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titlebar_docadvice_img_back:
                finish();
                break;
            case R.id.sure:
                if(AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().getNursesSign()!=null) {
                    insertContent();
                }
                else {
                    dialog = new ClickDialog(aty).builder().setTxt("存在未签名,是否提交？");
                    dialog.isCancleBack(true);
                    dialog.setCallBack(new ClickDialog.ICallBack() {
                        @Override
                        public void callback(Bundle bundle) {
                            if(bundle.getInt("data") == 0){
                                insertContent();
                            } else if(bundle.getInt("data") == 1){
                                dialog.dismiss();
                            }

                        }
                    });
                    dialog.show();
                }
                break;
            case R.id.btn_ra_sign_03:
                showTypeDialog();
                break;
        }
    }

    private void insertContent() {
        for (int i = 0; i < AppConfig.RISKASSESSMENTBEAN.getObject().getRiskItemList().size(); i++) {
            switch (AppConfig.RISKASSESSMENTBEAN.getObject().getRiskItemList().get(i).getItemCode()) {
                case "SJ_T":
                    if (radio01.isChecked()) {
                        AppConfig.RISKASSESSMENTBEAN.getObject().getRiskItemList().get(i).setItemValue("1;0");
                        int score;
                        if (AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().getRiskScore() == null) {
                            score = 0;
                        } else {
                            score = Integer.valueOf(AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().getRiskScore());
                        }
                        score = score - original_score;
                        AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().setRiskScore(score + "");
                    }
                    if (radio02.isChecked()) {
                        AppConfig.RISKASSESSMENTBEAN.getObject().getRiskItemList().get(i).setItemValue("2;1");
                        int score;
                        if (AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().getRiskScore() == null) {
                            score = 0;
                        } else {
                            score = Integer.valueOf(AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().getRiskScore());
                        }
                        score = score + 1 - original_score;
                        AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().setRiskScore(score + "");
                    }
            }
        }

        if (AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().getRiskId() == null) {
            Map<String, String> params = new HashMap<>();
            params.put("operationNo", PreferenceHelper.readString(aty, AppConfig.PATIENT_INFO, AppConfig.PATIENT_OPERATION_ID) + "");
            params.put("saveData", JSON.toJSONString(AppConfig.RISKASSESSMENTBEAN));
            presenter.insertRiskAssessmentDate(params);
        } else {
            Map<String, String> params = new HashMap<>();
            params.put("accountId", PreferenceHelper.readInt(aty, AppConfig.USER_INFO, AppConfig.USER_ACCOUNT) + "");
            params.put("fullName", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.USER_FULLNAME) + "");
            params.put("saveData", JSON.toJSONString(AppConfig.RISKASSESSMENTBEAN));
            presenter.updateRiskAssessmentDate(params);
        }
    }


    @Override
    public void insertRiskAssessmentDate(SubmitBean submitBean) {
        if (submitBean.getCode() == 200) {
            ViewInject.toast("保存成功");
            finish();
        } else {
            ViewInject.toast(submitBean.getDesc());
        }
    }

    @Override
    public void updateRiskAssessmentDate(SubmitBean submitBean) {
        if (submitBean.getCode() == 200) {
            ViewInject.toast("保存成功");
            finish();
        } else {
            ViewInject.toast(submitBean.getDesc());
        }
    }

    @Override
    public void loadingDialogStatus(int status) {
        switch (status) {
            case AppConfig.SHOW_DIALOG:
                loadingDialog.setCanceledOnTouchOutside(false);
                loadingDialog.show();
                break;
            case AppConfig.DISMISS_DIALOG:
                loadingDialog.dismiss();
                break;

        }
    }

    private void showTypeDialog() {
        ActionSheetDialog actionSheetDialog;
        actionSheetDialog = new ActionSheetDialog(this).builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true);
        actionSheetDialog.addSheetItem("HIS签名", ActionSheetDialog.SheetItemColor.Blue,
                new ActionSheetDialog.OnSheetItemClickListener() {
                    @Override
                    public void onClick(int which) {
                        loginDialog.builder();
                        loginDialog.show();
                        loginDialog.setCallBack(new LoginDialog.ICallBack() {
                            @Override
                            public void callback(Bundle bundle) {
                                Map<String, String> params = new HashMap<>();
                                params.put("jobNum", bundle.getString("person_num"));
                                params.put("loginPwd", bundle.getString("person_psw"));
                                presenter_sign.getSignInfo(params);
                            }
                        });
                    }
                });
        actionSheetDialog.addSheetItem("虹膜签名(暂不可用)", ActionSheetDialog.SheetItemColor.Blue,
                new ActionSheetDialog.OnSheetItemClickListener() {
                    @Override
                    public void onClick(int which) {

                    }
                });
        actionSheetDialog.show();
    }

    @Override
    public void getSignInfo(SignBean signBean) {
        loginDialog.dismiss();
        if (signBean.getCode() == 200) {
            if (signBean.getObject().getDoctorType().equals("H")) {
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault());
                Date curDate = new Date(System.currentTimeMillis());//获取当前时间
                String str = formatter.format(curDate);
                imgRaSign03.setVisibility(View.VISIBLE);
                Glide.with(this)
                        .load(signBean.getObject().getSignPicture())
                        .placeholder(R.color.white)
                        .error(R.color.white)
                        .into(imgRaSign03);
                btnRaSign03.setVisibility(View.GONE);
                tvRaSign03Time.setVisibility(View.VISIBLE);
                tvRaSign03Time.setText("签名时间:" + str);
                tvRaSign03Name.setVisibility(View.VISIBLE);
                tvRaSign03Name.setText(signBean.getObject().getDoctorName());

                AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().setNursesSign(signBean.getObject().getDoctorName());
                AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().setNursesSignUrl(signBean.getObject().getSignPicture());
                AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().setNursesSignTimeStr(str);
            } else {
                ViewInject.toast("请使用护士账号进行签名");
            }
        } else {
            ViewInject.toast(signBean.getDesc());
        }
    }

    /**
     * 通过dispatchTouchEvent每次ACTION_DOWN事件中动态判断非EditText本身区域的点击事件，然后在事件中进行屏蔽。然后当点击不是EditText时候，进行隐藏键盘操作
     *
     * @param ev
     * @return
     */

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {

        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件\
                return false;
            } else {
                return true;
            }
        }
        return false;
    }
}
